package com.atguigu.spzx.manager.task;

import cn.hutool.core.date.DateUtil;
import com.atguigu.spzx.manager.mapper.OrderInfoMapper;
import com.atguigu.spzx.manager.mapper.OrderStatisticsMapper;
import com.atguigu.spzx.model.entity.order.OrderStatistics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class OrderStatisticsTask {
    @Autowired
    OrderInfoMapper orderInfoMapper;
    @Autowired
    OrderStatisticsMapper orderStatisticsMapper;
    //    每隔5秒执行一次
//    cron表达式
//    @Scheduled(cron = "0/5 * * * * ? ")
//    public void testHello() {
//        System.out.println(new Date().toInstant());
//    }

    //    每天的凌晨2点，查询前一天统计数据，把统计数据加入数据库
    @Scheduled(cron = "0 0 2 * * ?")
//    @Scheduled(cron = "0/5 * * * * ? ") // 为了测试
    public void orderTotalAmountStatistics() {
        System.out.println(new Date().toInstant());
//        1.获取前一天日期
        String createDate = DateUtil.offsetDay(new Date(), -1).toString("yyyy-MM-dd");

//        2.根据前一天日期进行统计功能(分组操作)
        OrderStatistics orderStatistics = orderInfoMapper.selectOrderStatistics(createDate);
//        统计前一天交易金额
        if (orderStatistics != null) {
            orderStatisticsMapper.insert(orderStatistics);
        }
    }
}
